﻿using System;
using System.Linq;
using RayD.Core;
using Castle.DynamicProxy;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Reflection;
using Autofac;
using RayD.App.SystemModule;
using System.Text;
using StackExchange.Profiling;

namespace RayD.App.Setup
{
    /// <summary>
    /// Api性能分析切面
    /// </summary>
    public class ApiMiniProfilerInterceptor : IInterceptor
    {

        /// <summary>
        /// 实例化IInterceptor唯一方法 
        /// </summary>
        /// <param name="invocation">包含被拦截方法的信息</param>
        public void Intercept(IInvocation invocation)
        {
            //过滤Service方法：记录日志
            bool boolean = invocation.InvocationTarget.GetType() == typeof(LogApp)
                            && invocation.Method.Name == "WriteLog";
            if (!boolean)
            {
                try
                {
                    //记录当前执行Service方法
                    MiniProfiler.Current.Step($"执行Service方法：{invocation.Method.Name}() -> ");
                    //在被拦截的方法执行完毕后 继续执行当前方法，注意是被拦截的是异步的
                    invocation.Proceed();
                }
                catch (Exception ex)
                {
                    //执行的 service 中，收录异常
                    MiniProfiler.Current.CustomTiming("Errors：", ex.Message);
                    throw;
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
